package com.shawn.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.shawn.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class VisitorsApiImpl implements VisitorsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取四条最近访客记录
     *
     * @param userId 用户id
     * @return {@link List}<{@link Visitors}>
     */
    @Override
    public List<Visitors> getVisitors(Long userId,Long lastLookTime) {
        Query query = new Query();
        if (lastLookTime!=0){
            //如果上次查看时间不为0
            query.addCriteria(Criteria.where("date").gt(lastLookTime));
        }
        query.addCriteria(Criteria.where("userId").is(userId))
                .addCriteria(Criteria.where("visitorUserId").ne(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .limit(4);
        return mongoTemplate.find(query, Visitors.class);
    }

    /**
     * 保存访问者
     *
     * @param vi 6
     */
    @Override
    public void save(Visitors vi) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(vi.getUserId()))
                .addCriteria(Criteria.where("visitorUserId").is(vi.getVisitorUserId()));
        boolean exists = mongoTemplate.exists(query, Visitors.class);
        if (exists){
            //存在即更新
            Update update = new Update();
            update.set("date",vi.getDate())
                    .set("from",vi.getFrom())
                    .set("visitDate",vi.getVisitDate());
            mongoTemplate.updateFirst(query,update,Visitors.class);
        }else {
            //不存在即保存
            mongoTemplate.save(vi);
        }
    }

    @Override
    public List<Long> getAllVisitors(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId)).addCriteria(Criteria.where("visitorUserId").ne(userId));
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
       return visitors.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());
    }
}
